package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
//        //精准清理缓存
//        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");

        return R.success("新增菜品成功");
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "dishCache",allEntries = true)
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);


        //清除缓存方式
        //1.全局清理
//        Set keys = redisTemplate.keys("dish_*");
//        redisTemplate.delete(keys);

//        //精准清理
//        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");

        return R.success("修改菜品成功");
    }

    /**
     * 菜品分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){

        //一:菜品分页基础查询
        //分页构建器
        Page<Dish> dishPage = new Page<>(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);

        //查询
        dishService.page(dishPage,lqw);

        //二,处理分页集合数据
        Page<DishDto> dishDtoPage = new Page<>();
        //1. 复制分页信息（排除分页几何数据，因为缺少分类名称）
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        //2.把集合数据单独出来
        //2.1获取原始的dishPage分页对象中集合数据
        List<Dish> records = dishPage.getRecords();

        List<DishDto> dtoList = new ArrayList<>();
        //2.2遍历集合
        records.forEach(dish -> {
            //创建一个DishDto对象
            DishDto dishDto = new DishDto();
            //复制dish数据到dishDto
            BeanUtils.copyProperties(dish,dishDto);
            //查询分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            //设置分类名称到dishDto中
            if (category != null){
                dishDto.setCategoryName(category.getName());
            }
            dtoList.add(dishDto);
        });
        //将处理后的集合，添加到分页对象中
        dishDtoPage.setRecords(dtoList);

        return R.success(dishDtoPage);
    }


    @GetMapping("/{id}")
    @Cacheable(value = "dishCache",key = "#id")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishdto = dishService.getByIdWithFlavor(id);
        return R.success(dishdto);
    }


    /**
     * 返回分类信息
     * @param dish
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "dishCache",key = "#dish.categoryId")
    public R<List<DishDto>> list(Dish dish){
//        //查询redis缓存
//        String key = "dish_" + dish.getCategoryId() + "1";
//        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
//        //判断缓存是否有内容
//        //1.若有
//        if (dishDtoList!=null){
//            return R.success(dishDtoList);
//        }
//        //若无

        //条件构建器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        lqw.eq(Dish::getStatus,1);
        List<Dish> list = dishService.list(lqw);
        //复制Dish-->DishDto
        List<DishDto> dtoList = new ArrayList<>();

        list.forEach(dish1 -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(dish1,dishDto);

            LambdaQueryWrapper<DishFlavor> laq = new LambdaQueryWrapper<>();
            laq.eq(DishFlavor::getDishId,dish1.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(laq);
            dishDto.setFlavors(flavorList);

            dtoList.add(dishDto);
        });
//        //将数据放入缓存
//        redisTemplate.opsForValue().set(key,dtoList,1, TimeUnit.HOURS);
        return R.success(dtoList);
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    public R<String> delectDish(@RequestParam List<Long> ids){
        dishService.removeWithdish(ids);
        return R.success("删除菜品成功");
    }

    /**
     * 批量修改启售/停售
     */
    @CacheEvict(value = "dishCache",key = "#dishDto.categoryId")
    @PostMapping("/status/{type}")
    public R<String> updatestatus(@PathVariable int type ,@RequestParam List<Long> ids){
        ids.forEach(id->{
            Dish dish = dishService.getById(id);
            if (type == 1){
                dish.setStatus(1);
            }else {
                dish.setStatus(0);
            }
            dishService.updateById(dish);
        });

        return R.success("修改成功");
    }

}
